//
//  XXArray.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/28.
//

import Foundation

public extension Array {

    typealias XXArrayEchoBlock = (Int,Any)->Bool
    
    var data:Data?{
        var data: Data?
        try? data = JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
        return data
    }
    
    var json:String {
        if let d = self.data{
            guard let jsonStr = String.init(data: d, encoding: .utf8) else{
                return ""
            }
            return jsonStr
        }else{
            return ""
        }
    }
    
//    func modelArr<T: HandyJSON>(_ model: T.Type) -> Array<T>  {
//        let modelArr:Array<T> = JSONDeserializer<T>.deserializeModelArrayFrom(array: self) as! Array<T>
    //        return modelArr
//    }

//    subscript (_ index:Int) -> Element?{
//        return self.value(index)
//    }
    func value (_ index: Int) -> Element? {
        return index >= 0 && index < count ? self[index] : nil
    }
    
    func string(_ index:Int) -> String {
        if !(self[index] is NSNull) {
            let obj = self[index]
            return obj as! String
        }
        return ""
    }
    
    func merge(_ arr:Array<Any>) -> Array<Any> {
        var newArr:Array<Any> = self
        for obj in arr{
            newArr.append(obj)
        }
        return newArr
    }
    func echo(_ block:XXArrayEchoBlock){
        for i in 0..<self.count{
            if !block(i,self[i]) {
                break
            }
        }
    }
    subscript(nullable index:Int) -> Element?{
        if(startIndex..<endIndex).contains(index){
            return self[index]
        }
        return nil
    }
    subscript(string index:Int) -> String{
        if let value = self[nullable: index]{
            let type = type(of: value)
            if type == String.self{
                return value as! String
            }else if type == Int.self{
                let int = value as! Int
                return int.string
            }else if type == Float.self{
                let float = value as! Float
                return float.string
            }else if type == Double.self{
                let double = value as! Double
                return double.string
            }
        }
        return ""
    }
}
